
var widget;
var widgetWidth;
var widgetHeight;
var newRating = 0;
var widget_id;

function WidgetViewPageBuilder() {
	PageBuilder.call(this);
}

WidgetViewPageBuilder.prototype = new PageBuilder();

WidgetViewPageBuilder.prototype.constructor = WidgetViewPageBuilder;

WidgetViewPageBuilder.prototype.build = function() {
	$("#owner_label").html(getDisplayString("owner_caption"));
	$("#type_label").html(getDisplayString("type_caption"));
	$("#uploaded_label").html(getDisplayString("uploaded_caption"));
	$("#updated_label").html(getDisplayString("updated_caption"));
	
	$("#viewwidget_label").html(getDisplayString("viewwidget_caption"));
	$("#embedcode_label").html(getDisplayString("embedcode_caption"));
	$("#averagerating_label").html(getDisplayString("averagerating_caption"));
	$("#yourrating_label").html(getDisplayString("yourrating_caption"));
	$("#editfunctionalities_label").html(getDisplayString("editfunctionalities_caption"));
	$("#functionalities_button").html(getDisplayString("functionalities_title"));
	$("#tags_label").html(getDisplayString("tags_caption"));
	$("#tags_select_label").html(getDisplayString("tags_select_caption"));
	
	$("#tagchoose_button").html(getDisplayString("choosebutton_caption"));
	$("#tagcreate_label").html(getDisplayString("tagcreate_caption"));
	$("#savetag_button").html(getDisplayString("savebutton_caption"));
	$("#reviews_label").html(getDisplayString("reviews_caption"));
	$("#review_instruction").html(getDisplayString("reviewinstruction_text"));
	$("#savereview_button").html(getDisplayString("savebutton_caption"));
	$("#review_message").html(getDisplayString("reviewmessage_text"));
}


$(document).ready(function() {
	setLogin();
	buildPage ( new WidgetViewPageBuilder() );
	widget_id = getQueryVariable("widgetId");
	getWidget ( widget_id );
	getReviewsForWidget ( widget_id );
	registerResponderForSignal ( "tagsChanged", reloadWidget);
	registerResponderForSignal ( "tagsNotChanged", displayMessage );
	registerResponderForSignal ( "newRating", showRating );
	registerResponderForSignal ( "userLoggedIn", getUserRating );
	getAllTags();
	getPopularTags();
	iwc_call_name = getCookie("iwc_call_name");
	workspace_widget_specifier = getCookie("workspace_widget_specifier");
	var installbutton_label = getDisplayString("installbutton_caption");
	if ( iwc_call_name != null ) {
		$("#install_button").html ('<div class="wi_label_left"><div class="wi_label">Install Widget: </div><div class="wi_text"><button onClick="installWidget()">'+installbutton_label+'</button></div><div class="clear"></div></div>');
	}
	$("#searchText").on('keydown', function(e) {
		if ( e.which == 13 ) {
			e.preventDefault();
			searchStore();
		}
	});
	$("#average-rating").raty({
		readOnly: true
	});
	
	$("#your-rating").raty({
		click: function ( score, evt ) {
			setUserRatingForWidget (score);
		}
	});
	
	$("#embedDialog").dialog({
		autoOpen: false,
		height: 250,
		width: 450,
		modal: true
	});
	
	$("#viewDialog").dialog({
		autoOpen: false,
		modal: true
	});

	
});

function showRating ( rating ) {
	$("#your-rating").raty('score', rating);
	getAverageRatingForAWidget(widget_id);
}

function installWidget () {
	var data = new Object();
	data.workspace_widget_specifier = workspace_widget_specifier;
	data.widgetIRI  = widget.widgetProfile.uri;
	data.widgetTitle = widget.widgetProfile.name;
	var jsonData = JSON.stringify(data);
	pmrpc.call({
		destination: "publish",
		publicProcedureName: iwc_call_name,
		params : [jsonData],
	});
}


function addReview() {
	var reviewdata = $("#review-text").attr('value');
	addNewReview ( reviewdata );
}

function displayMessage ( messageString ) {
	alert ( messageString );
}

function reloadWidget () {
	if ( widget_id ) {
		getWidget(widget_id);
		getAllTags();
		getPopularTags();
	}
}

function saveTag() {
	var tagtext = $("#tag-text").attr('value');
	addNewTag ( widget_id, tagtext );
}

function getUserRating ( ) {
	getUserRatingForWidget();
}




function goToFunctionalities() {
	window.location = "widget_functionalities.html?widgetId="+widget.widgetProfile.id;
}

function getWidget ( widget_id ) {
	$.ajax({
		type:"GET",
		url:store_rest_url+"/widgets/"+widget_id,
		dataType: "text",
		success: showWidget
	});
}

function viewWidget () {
	// get the width from the iframe info
	//var render = w.renderInfo;
	
	incrementWidgetStats(widget_id, "views");
	
	$("#viewContents").html(widget.renderInfo+'<button onClick="setWidgetFavourite('+widget_id+')">Favourite</button>');
	var wid = $("#viewContents > iframe").width() + 34;
	$("#viewDialog").dialog("option","title", widget.widgetProfile.name );
	$("#viewDialog").dialog("option","width", wid );
	$("#viewDialog").dialog("open");
}

function embedCode () {
	
	incrementWidgetStats(widget_id, "embeds");
	
	$("#embedContent").text(widget.renderInfo);
	$("#embedDialog").dialog("open");
}

function showWidget ( widgetJSON ) {
	widget = $.parseJSON ( widgetJSON );
	renderWidget ( widget );
	var tags = widget.widgetProfile.tags;
	if ( tags ) {
		var tagsHTML = '';
		for(var i=0;i<tags.length;i++){
			var tag=tags[i];
			tagsHTML += renderTag(tag);
		}
		tagsHTML += '<div style="clear: both;"></div>';
		$("#tag-list").html(tagsHTML);
	}
	var functionalities = widget.widgetProfile.functionalities;
	if ( functionalities ) {
		var fHTML = '';
		for ( var i=0;i<functionalities.length;i++){
			var f = functionalities[i];
			fHTML += renderFunctionality(f);
		}
		fHTML += '<div style="clear: both;"></div>';
		$("#functionalities-list").html(fHTML);
	}
	if ( widget.averageRating ) {
		$("#average-rating").raty('readOnly', false);
		$("#average-rating").raty('score', widget.averageRating);
		$("#average-rating").raty('readOnly', true);
	}
	if ( getUser() != null ) {
		getUserRatingForWidget();
	}
	//getWookieWidgetInfo ( widget.widgetProfile.uri);
}


function renderWidget (widget) {
	var profile = widget.widgetProfile;
    //$("#results_title").html("<a href=\"javascript:backToList()\">"+savedResultsTitle+"</a>&nbsp;"+profile.name);
	var iconPath;
	if ( profile.icon == null || profile.icon == "" ) {
		iconPath = "img/default_widget_icon.png";
	}
	else {
		iconPath = profile.icon;
	}
	$(".wi_icon").html('<img src="'+iconPath+'" alt="Widget Icon"/>');
	$(".wi_title").html(profile.name);
	$(".wi_description").html(profile.description);
	if ( widget.owner ) {
		$("#wi_author").html(widget.owner.accountinfo.realname);
	}
	$("#wi_created").html(profile.created);
	$("#wi_updated").html(profile.updated);
	$("#wi_type").html(profile.type);
	
}

function renderTag(tag) {
	var tagHTML = '<div class="tag-box">'+tag.tagtext+'<span class="logged-in"';
	if ( !userCanEdit () ) {
		tagHTML += ' style="display: none;"';
	}
	tagHTML += '>&nbsp;<img src="img/close-icon.png" onclick="removeTag('+tag.id+','+widget.widgetProfile.id+')" style="cursor:pointer;"/></span></div>';
	return tagHTML;
}

function renderFunctionality(f) {
	var html = '<div class="functionality_block">'+f.name+' <span id="pos'+f.id+'">'+f.relevance+'%</span></div>';
	return html;
}


function removeTag ( tag_id, widget_id ) {
	removeTagFromWidget ( tag_id, widget_id );
}
function getReviewsForWidget( widget_id ) {
	$.ajax({
		type:"GET",
		url:store_rest_url+"/reviews/"+widget_id,
		dataType: "text",
		success: showReviews
	});
}

function showReviews(jsonString) {
	var reviewList = $.parseJSON(jsonString);
	buildReviewList(reviewList);
	//$("#reviewList").html(html);
}


function buildReviewList ( reviewList ) {
	count = 0;
	for(var i=0;i<reviewList.length;i++) {
		var review = reviewList[i];
		var user = review.userFullName;
		var dateTime = review.time;
		var comment = review.text;
		var html = '<div class="review-box">';
		html += '<div class="review-user">'+user+'</div>';
		html += '<div class="review-date">'+dateTime+'</div>';
		html += '<div id="review'+i+'" class="review-body"></div>';
		html += '</div>';
		$("#reviewList").append(html);
		$("#review"+i).text(comment);
		count++;
		
	}
	$("#numberOfReviews").html(count);
}

function addNewReview ( reviewText ) {
	var u = getUser();
	if ( u == null ) {
		alert ( "Cannot review without logging in!");
		return;
	}
	if ( widget == null ) {
		alert ("There is no widget to review!");
		return;
	}
	var widget_id = widget.widgetProfile.id;
	var username = u.username;
	$.ajax({
		type: "POST",
		url:store_rest_url+"/reviews/edit/"+widget_id,
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		},
		data: {comment: reviewText},
		dataType: "text",
		success: reviewStored
	});
}


function reviewStored ( jsonString ) {
	getReviewsForWidget ( widget.widgetProfile.id);
}

// wookie stuff

function getWookieWidgetInfo (uri) {
	$.ajax({
		type:"GET",
		url:wookie_url+"/widgets/"+uri+"?locale=en",
		dataType: "html",
		success: wookieWidgetInfo
	});
}


function wookieWidgetInfo ( xmlText ) {
	var widgetXML = $.parseXML(xmlText);
	var author = $(widgetXML).find("author").text();
	if ( author != null ) {
		$("#wi_widgetauthor").html(author);
	}
	var widgetWidth = $(widgetXML).find("widget").attr("width");
	var widgetHeight = $(widgetXML).find("widget").attr("height");
}


function getAverageRatingForAWidget ( widgetId ) {
	$.ajax({
		type: "GET",
		url: store_rest_url+"/ratings/average/"+widgetId,
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		},
		dataType: "text",
		success: updateAverageRatingView
	});
}


function updateAverageRatingView ( inJSON ) {
	var n = $.parseJSON(inJSON);
	$("#average-rating").raty('readOnly', false);
	$("#average-rating").raty('score', n);
	$("#average-rating").raty('readOnly', true);
}